import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue')
    },
    {
        path: '/in',
        name: 'StorageIn',
        component: () => import('@/views/StorageIn.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/out',
        name: 'StorageOut',
        component: () => import('@/views/StorageOut.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/fee',
        name: 'FeeManagement',
        component: () => import('@/views/FeeManagement.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/reports',
        name: 'Reports',
        component: () => import('@/views/Reports.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/',
        redirect: '/dashboard'
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: '/dashboard'
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    
    if (to.meta.requiresAuth && !userStore.token) {
        next('/login')
    } else if (to.path === '/login' && userStore.token) {
        next('/in')
    } else {
        next()
    }
})

export default router